#include "./src/shared.h"
#include "./src/types.h"

uniform float lightScale;

// Deferred shader textures
samplerRect dsEC;
samplerRect dsNorm;
samplerRect dsColor;

// Index into the light textures
uniform vec2 lightIndex[LIGHTS_PER_PASS];
samplerRect lightPos;
samplerRect lightDir;
samplerRect lightColor;
samplerRect prevIndirect;
uniform float prevScale;
uniform float spotCosCutoff;
uniform float cAtt;
uniform float lAtt;
uniform float qAtt;

void main (void)
{
	vec4 indirectColor = vec4(0,0,0,0);

	vec3 n = normalize(textureRect(dsNorm, gl_FragCoord));
	vec3 position = textureRect(dsEC, gl_FragCoord);
	vec4 diffuse = textureRect(dsColor, gl_FragCoord);

	for (int i=0; i<LIGHTS_PER_PASS; ++i) {
		vec3 lightPosition = textureRect(lightPos, lightIndex[i]);
		// Required offset when lights are determined from the camera...
		lightPosition.z += 0.001;
		vec3 lightDirection = textureRect(lightDir, lightIndex[i]);
		vec4 lightDiffuse = textureRect(lightColor, lightIndex[i]);
		vec3 toLight = lightPosition - position;
		float dis = length(toLight);
		toLight = normalize(toLight);
		// TODO normalize required?
		//float spotDot = dot(-toLight, normalize(lightDirection));
		float nDotL= max(0.0, dot(n,toLight));
		float att, spotAtt=1;
#if 0
		if (spotDot < spotCosCutoff) {
			spotAtt = 0.0;
		} else {
			spotAtt = pow(spotDot, 1.0); //gl_LightSource[0].spotExponent);
		}
#endif
		att = spotAtt * 1/(cAtt + lAtt*dis + qAtt*dis*dis);
		indirectColor += lightDiffuse * nDotL * att;
	}
	//indirectColor *= diffuse;

	gl_FragData[0] = prevScale * textureRect(prevIndirect, gl_FragCoord) + indirectColor * lightScale;
}

